package ejb;

import java.util.Date;
import java.util.Timer;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Singleton;
import javax.ejb.TimerService;




@Singleton
@LocalBean
public class TimeManager {
	
	@Resource 
	private TimerService timerService;
	@EJB
	private VoteCounter voteCounter;
	
	private javax.ejb.Timer electionDay;
	private javax.ejb.Timer candidacyStart;
	private javax.ejb.Timer candidacyEnd;
	
	private boolean acceptsEnabled;
	private boolean votesEnabled;
	
	private boolean electionFinished;
	private boolean governorElected;
	
	public boolean isGovernorElected(){
		return governorElected;
	}
	public synchronized void setGovernorElected(boolean governorElected){
		this.governorElected = governorElected;
	}
	
	//----- Setting dates for the candidacy period
	public void setCandidacyPeriod(Date startCandidacy, Date endCandidacy){
		Date start = null;
		Date end = null;
		
		if(startCandidacy.before(endCandidacy)){
			start = startCandidacy;
			end = endCandidacy;
		}
		else{
			start = endCandidacy;
			end = startCandidacy;
		}
		if (candidacyStart !=null){
			candidacyStart.cancel();
		}
		if(candidacyEnd !=null){
			candidacyEnd.cancel();
		}
		candidacyStart = timerService.createTimer(start, "CandidacyStart");
		candidacyEnd = timerService.createTimer(end, "CandidacyEnd");
		
	}
	//-------Setting the date for the election
	public void setDateElection(Date dateElection){
		Date dateElect;
		dateElect = dateElection;
		if(electionDay !=null){
			electionDay.cancel();
		}
		electionDay = timerService.createTimer(dateElect, "24hours");
	}
	
	
	
	public boolean areAcceptsEnabled(){
		return acceptsEnabled;
	}
	public boolean areVotesEnabled(){
		return votesEnabled;
	}
	public boolean areElectionsEnded(){
		return electionFinished;
	}
	
}
